import { login, logout, getInfo ,getMenus} from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_MENU: (state, menu) => {
    state.menu = menu
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { account, password,captcha } = userInfo
    return new Promise((resolve, reject) => {
      login({ account: account.trim(), password: password,captcha: captcha }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.tokenValue)
        setToken(data.tokenValue)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response

        if (!data) {
          return reject('验证失败，请重新登录!')
        }

        const { account, avatar } = data

        commit('SET_NAME', account)
        commit('SET_AVATAR', 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif')
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken()
      resolve()
    })
  },



    // get user info
    getMenus({ commit }) {
      return new Promise((resolve, reject) => {
        getMenus().then(response => {
          const { data } = response
  
          if (!data) {
            return reject('获取菜单失败!')
          }
          
          const routes = generaMenu([],data)
        
          commit('SET_MENU', routes)
          resolve(data)
        }).catch(error => {
          reject(error)
        })
      })
    },


}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}


/**
 * 后台查询的菜单数据拼装成路由格式的数据   // npm install  babel-eslint@7.2.3  --registry=https://registry.npm.taobao.org
 * @param routes
 */
 export function generaMenu(routes, data) {

  data.forEach(item => {
    // alert(JSON.stringify(item))

    console.log(`@/views/${item.component}`)
    //item.component = 'nested/menu1/index';
    //item.component = 'tree/index';

    const menu = {
      path: item.path,
      // component:  () => import('@/views/nested/menu1/index'),
       //component: item.component === '' ? Layout : () => import(`@/views${item.component}`),
      //component: () => import(`@/views/${item.component}`),
      component: (resolve) => require([`@/views/${item.component}`], resolve),
      //component:()=>resolve=>require([`@/views/${item.component}`],resolve) ,


      hidden: item.isShow == true ? false : true,
      redirect: item.redirect,
      children: [],
      name: 'menu_' + item.id,
      //meta: item.meta
      // meta: { title: item.name, id: item.id, roles: ['admin'] }
       meta: { title: item.name, id: item.id }
    }

    if (item.treeList) {
      generaMenu(menu.children, item.treeList)
    }
    routes.push(menu)
  })

  return routes
}
